const bcrypt = require('../server/node_modules/bcrypt');
const path = require('path');
const sqlite3 = require('sqlite3').verbose();

// 连接到数据库
const dbPath = path.join(__dirname, '../resources/db/db.database');
console.log('Database path:', dbPath);

const db = new sqlite3.Database(dbPath);

// 迁移密码
async function migratePasswords() {
    try {
        // 获取所有用户
        const users = await new Promise((resolve, reject) => {
            db.all('SELECT id, username, password FROM users', [], (err, rows) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(rows);
                }
            });
        });

        console.log(`Found ${users.length} users. Checking passwords...`);

        let migratedCount = 0;
        for (const user of users) {
            // 如果密码不是bcrypt格式（不以$2开头），则进行迁移
            if (!user.password.startsWith('$2')) {
                console.log(`Migrating password for user: ${user.username}`);
                
                // 哈希密码
                const hashedPassword = await bcrypt.hash(user.password, 10);
                
                // 更新数据库
                await new Promise((resolve, reject) => {
                    const stmt = db.prepare('UPDATE users SET password = ? WHERE id = ?');
                    stmt.run([hashedPassword, user.id], function(err) {
                        if (err) {
                            reject(err);
                        } else {
                            console.log(`Updated password for user ${user.username}`);
                            migratedCount++;
                            resolve();
                        }
                    });
                    stmt.finalize();
                });
            }
        }
        
        console.log(`Migration completed. ${migratedCount} passwords were updated.`);
        db.close();
    } catch (error) {
        console.error('Error during migration:', error);
        db.close();
    }
}

migratePasswords();